package runtime

import (
	"fmt"

	"gitee.com/shoyer/framework/keys"
	"gitee.com/shoyer/logger"
	"gitee.com/shoyer/service/config"
	"gitee.com/shoyer/service/rdb"
	"gitee.com/shoyer/util"
)

// IsMaster IsMaster
func IsMaster() bool {
	return GetServerIP() == config.GetMasterIP()
}

// IsServerOnline IsServerOnline
func IsServerOnline(server, port string) bool {
	url := fmt.Sprintf("http://%s:%s/op/getOnlineStatus", server, port)
	result, err := util.Get(url)
	if err != nil {
		logger.Error("服务器检测故障，执行从rdb中删除操作", err)
		rdb.GetMaster().HDel(rdb.GetKey(keys.OnlineServers), server).Result()
		return false
	}

	if result != "0" { // 0 代表健康在线。
		logger.Error("服务器检测故障，执行从rdb中删除操作", " 代码不为0，不在线")
		rdb.GetMaster().HDel(rdb.GetKey(keys.OnlineServers), server).Result()
		return false
	}

	logger.Infof("服务器在线" + url)

	return true
}

// IsServerItSelf IsServerItSelf
func IsServerItSelf(server string) bool {
	return GetServerIP() == server
}

// IsServerInChina 判断服务器是否在中国
func IsServerInChina() bool {
	if IsLocal() {
		return true
	}

	servers := config.GetConfigChinaServers()
	currentServer := GetServerIP()

	for _, server := range servers {
		if server == currentServer {
			return true
		}
	}

	return false
}

// IsServerWillMaintenance IsServerWillMaintenance
func IsServerWillMaintenance() bool {
	return GetServerMaintenanceStartAt() >= util.GetTimestamp()
}

// IsServerInMaintenance IsServerInMaintenance
func IsServerInMaintenance() bool {
	now := util.GetTimestamp()
	return GetServerMaintenanceEndAt() >= now && now >= GetServerMaintenanceStartAt()
}

// GetServerMaintenanceEndAt 通过本地rdb获取状态, 以获取最快访问速度，如果需要维护，用个接口把维护的状态同步到每台服务器的rdb.
func GetServerMaintenanceEndAt() int64 {
	endAt, _ := rdb.GetDB().Get(rdb.GetKey(keys.MaintenanceEndAt)).Int64()
	return endAt
}

// GetServerMaintenanceStartAt 通过本地rdb获取状态, 以获取最快访问速度，如果需要维护，用个接口把维护的状态同步到每台服务器的rdb.
func GetServerMaintenanceStartAt() int64 {
	startAt, _ := rdb.GetDB().Get(rdb.GetKey(keys.MaintenanceStartAt)).Int64()
	return startAt
}
